package cn.tuling.standard;

/**
 * 常规实现
 */
public class ChainOfResponsibilityTest {
    public static void main(String[] args) {
        Handler handlerA = new HandlerA();
        Handler handlerB = new HandlerB();
        handlerA.setNext(handlerB);

        // 可以处理
        handlerA.handle("one");
        handlerA.handle("two");
        // 无法处理
        handlerA.handle("txx");
    }
}

abstract class Handler {
    private Handler next;

    public Handler getNext() {
        return next;
    }

    public void setNext(Handler next) {
        this.next = next;
    }

    /**
     * 责任链 + 模板方法
     *
     * @param request
     */
    void handle(String request) {

        if (doHandle(request))
            return;

        if (getNext() != null)
            getNext().handle(request);
        else
            System.out.println("无法处理请求");
    }

    abstract boolean doHandle(String request);
}

class HandlerA extends Handler {

    @Override
    boolean doHandle(String request) {
        if (request.equalsIgnoreCase("one")) {
            System.out.println("HandlerA 处理了请求");
            return true;
        }
        return false;
    }
}

class HandlerB extends Handler {

    @Override
    boolean doHandle(String request) {
        if (request.equalsIgnoreCase("two")) {
            System.out.println("HandlerB 处理了请求");
            return true;
        }
        return false;
    }
}
